/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.refunite.mobile.webservice;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.JAXBException;
import org.apache.xerces.dom.ElementNSImpl;
import org.refunite.mobile.webservice.bindings.formgenerator.Html;
import org.refunite.mobile.webservice.formgenerator.CurrentForm;
import org.refunite.mobile.webservice.formgenerator.FormGenerator;

/**
 *
 * @author I040022
 */
@WebService()
public class RegistrationForm {

    private javax.xml.bind.JAXBContext jaxbCtxGenerator;
    private javax.xml.bind.JAXBContext jaxbCtxReceiver;
    private javax.xml.bind.Unmarshaller unmarshaller;
    private javax.xml.bind.Marshaller marshaller;


    public RegistrationForm() throws Exception{
        jaxbCtxGenerator = javax.xml.bind.JAXBContext.newInstance("org.refunite.mobile.webservice.bindings.formgenerator");
        jaxbCtxReceiver = javax.xml.bind.JAXBContext.newInstance("org.refunite.mobile.webservice.bindings.formreceiver");
        unmarshaller = jaxbCtxReceiver.createUnmarshaller();
        marshaller = jaxbCtxGenerator.createMarshaller();
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "saveRegistrationForm")
    public Boolean saveRegistrationForm(@WebParam(name = "formContent")
    String formContent) {
        System.out.println(formContent);
        if(formContent != null){
            try{
                org.refunite.mobile.webservice.bindings.formreceiver.RegistrationForm form = new org.refunite.mobile.webservice.bindings.formreceiver.RegistrationForm();
                ByteArrayInputStream bis = new ByteArrayInputStream(formContent.getBytes());
                form = (org.refunite.mobile.webservice.bindings.formreceiver.RegistrationForm)this.unmarshaller.unmarshal(bis);
                printContent(form);
                return true;
            }catch(JAXBException e){
                // TODO: do proper logging
                e.printStackTrace();
            }
        }
        return false;
    }


    private void printContent(org.refunite.mobile.webservice.bindings.formreceiver.RegistrationForm form){
        List<Object> inputData = form.getAny();
        for(Object o : inputData){
            ElementNSImpl element = (ElementNSImpl)o;
            System.out.println(element.getLocalName() + ": "+element.getTextContent());
        }
    }
    /**
     * Web service operation
     */
    @WebMethod(operationName = "getLatestRegistrationForm")
    public String getLatestRegistrationForm() {
        String retValue = "";
        Html form = FormGenerator.generateForm(CurrentForm.getCurrentFormStructure());
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",new MyNamespacePrefixMapperImpl());
            marshaller.setProperty(marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(form, outputStream);
            retValue = outputStream.toString("UTF-8");
        } catch (UnsupportedEncodingException usex) {
        } catch (javax.xml.bind.JAXBException ex) {
            // XXXTODO Handle exception
            java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
        }
        System.out.println("Form returned");
        return retValue;
    }

    public class MyNamespacePrefixMapperImpl extends NamespacePrefixMapper {
        public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
            if( "http://www.w3.org/1999/xhtml".equals(namespaceUri) )
                return "h";
            if( "http://www.w3.org/2001/xml-events".equals(namespaceUri) )
                return "ev";
            if( "http://www.w3.org/2001/XMLSchema".equals(namespaceUri) )
                return "xsd";
            if( "http://openrosa.org/javarosa".equals(namespaceUri) )
                return "jr";

           return suggestion;
       }

       public String[] getPreDeclaredNamespaceUris() {
           return new String[] {"http://www.w3.org/1999/xhtml", "http://www.w3.org/2001/xml-events", "http://www.w3.org/2001/XMLSchema", "http://openrosa.org/javarosa"};
       }
   }
}
